import Layout from '@/layout/index.vue'
import { createRouter, createWebHistory } from 'vue-router'
import { testRoutes } from './addRoute'
const routes = []
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
})

export const initRouter = (routers, path) => {
  routers.forEach((route) => {
    if (route.meta && route.meta.component) {
      route.component = loadView(route.meta.component)
    } else {
      route.component = Layout
    }
    if (path) {
      path === '/'
        ? (route.meta.url = path + route.path)
        : (route.meta.url = path + '/' + route.path)
    }
    if (route.children != undefined && route.children.length > 0) {
      initRouter(route.children, route.path)
    }
  })
}
const loadView = (view) => {
  return () => import(`@/views/${view}/index.vue`)
}

const test = [
  {
    path: '/',
    redirect: '/login',
  },
]

let menuTest = JSON.stringify([...test, ...testRoutes])
let menuJson = JSON.parse(menuTest) // 临时保存menu
// console.log(menuJson)
if (menuTest) {
  // 本地存在menu  加载路由信息
  initRouter(menuJson, undefined)
  menuJson.forEach((rt) => {
    // 添加路由信息到实例
    router.addRoute(rt)
  })
}

export default router
